

from rest_framework import serializers
from users.models import User
from django.contrib.auth.models import Group


class GroupSimpleModelSerializer(serializers.ModelSerializer):
    class Meta:
        model = Group
        fields = [
            'id',
            'name'
        ]


import re
from django.contrib.auth.hashers import make_password
class AdminUserModelSerializer(serializers.ModelSerializer):

    class Meta:
        model = User
        fields = [
            'id',
            'username',
            'email',
            'mobile',
            'password',

            'groups',
            'user_permissions'
        ]

        extra_kwargs = {
            'username': {'max_length': 20, 'min_length': 5},
            'password': {'max_length': 20, 'min_length': 8, 'write_only': True},
        }

    def validate_mobile(self, value):
        if not re.match(r'^1[3-9]\d{9}$', value):
            raise serializers.ValidationError('mobile格式有误')
        return value


    def validate(self, attrs):
        # 在校验的过程中加密密码
        # 1、提取明文密码
        raw_password = attrs.get('password') # 明文字符串密码"12345678"
        # 2、加密
        secret_password = make_password(raw_password) # 传入明文密码，得出密文密码
        # 3、把有效数据中的password设置为密文密码
        attrs['password'] = secret_password
        # 4、在有效数据中添加默认is_staff=True
        attrs['is_staff'] = True
        return attrs




